package server.business.play.script;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import server.ScriptEnum;
import server.ServerTransportProxy;
import server.business.poker.util.PokerGenerator;
import server.commonData.Player;
import server.commonData.PokerData;
import server.commonData.PokerPlayer;
import server.commonData.Table;
import server.commonData.User;
import server.messageId.S2CMessageId;
import server.msgBean.PlayMessage.PokersRes;

import com.core.initialize.Message;


/**
 * 打牌等待状态
 * @author King
 *
 */
public class PlayWaitScript implements IPlayGameScript
{

	@Override
	public int getId() {
		return ScriptEnum.PLAY_WAIT;
	}

	@Override
	public void onUpdate(Table table, long curmill)
	{
		Map<Long, PokerPlayer> players = table.getPlayers();
		if(!table.isFull())
			return;
		if(curmill<table.getZunbeiEndtime())
			return;
		for(PokerPlayer player:players.values())
		{
			player.setPlay(true);
		}
		
		int result [][] = null;
        Random r = new Random();
        int k = r.nextInt(100);
        PokerGenerator pg = PokerGenerator.getInstance();
        if (k<30){
            result = pg.getXiaoXiaoNiux();
        } else if(k>=30 && k<40){
            result = pg.getWuHua();
        } else if(k>=40 && k<50){
            result = pg.getBomb();
        } else if(k>=50 && k<60){
            result = pg.getNiuNiu();
        } else {
            result = pg.getCommonPokers();
        }
        
        //如果没有庄 随即出庄
		if(table.getZhuangPlayerId()==0)
		{
			List<PokerPlayer> playerList = new ArrayList<PokerPlayer>(players.values());
			table.setZhuangPlayerId(playerList.get(new Random().nextInt(playerList.size())).getPlayer().getId());
		}
		long xuanpaiEndTime=  System.currentTimeMillis()+20000;
	    //TODO 把一行给机器人
        int index = 0;
        for(PokerPlayer player:players.values())
		{
        	PokerData data =new PokerData();
        	player.setPokerData(data);
        	int[] pokers = result[index++];
        	data.setOwnPoker(pokers);
        	//发送获得牌给所有客户端
        	if(player.getPlayer().getType()==Player.USER)
        	{
        		Message msg = Message.newMessage();
        		msg.setModuleAction(S2CMessageId.PLAY.MODULE_ID, S2CMessageId.PLAY.POKERS_RES);
        		PokersRes.Builder builder = PokersRes.newBuilder();
        		builder.setXuanPaiEndTime(xuanpaiEndTime);
        		for(int poker:pokers)
        		{
        			builder.addPokerNum(poker);
        		}
        		builder.setZhuangId(table.getZhuangPlayerId());
        		msg.setBody(builder);
        		ServerTransportProxy.sendMsg(msg, (User)player.getPlayer());
        	}
		}
        table.setXuanpaiEndtime(xuanpaiEndTime);
        //切入下一个状态
        table.setStatus(ScriptEnum.PLAY_CHOOSE_POKER);
	}

}
